package pile;

import java.util.ArrayList;
import java.util.Random;

public class Environnement {

	public ArrayList<VariablePile> vars;
	public int nbVars;
	public ArrayList<EmplacementMemoire> memoire;
	public int nbMem;
	
	public Environnement() {
		vars = new ArrayList<VariablePile>();
		nbVars = 0;
		memoire = new ArrayList<EmplacementMemoire>();
		nbMem = 0;
	}
	
	public EmplacementMemoire getMem(int placeMem){
		EmplacementMemoire res = null;
		boolean found = false;
		int i = 0;
		while((i<memoire.size())&&(!found)){
			if(memoire.get(i).positionMem == placeMem){
				res = memoire.get(i);
				found = true;
			}
			i++;
		}
		return res;
	}
	
	public void createVar(String typeVar){
		nbVars++;
		nbMem++;
		String nom = "var_"+typeVar+"_"+nbVars;
		VariablePile newVar = new VariablePile(nbMem, typeVar,nom);
		vars.add(newVar);
		Random rand = new Random();
		String alphabet = "abcdefghijklmnopqrstuvwxyz{}@#!$%^&*()_+=";
		Integer valint = rand.nextInt(99);
		String valstring = valint.toString();
		char randchar = alphabet.charAt(rand.nextInt(alphabet.length()));
		String randstring = "'"+String.valueOf(randchar)+"'";
		String valeur = null;
		if(typeVar.equals("int")){
			valeur = valstring;
		}else{
			valeur = randstring;
		}
		EmplacementMemoire newMem = new EmplacementMemoire(newVar, nbMem, valeur);
		memoire.add(newMem);
	}
	
	public int equalVar(VariablePile var1, VariablePile var2){
		/* on pourrait renvoyer la place memoire liberee pour la faire tomber lors de l'affichage */
		/* retour = 0 signifie affectation impossible 
		 * retour = 1 signifie affectation effectuee */
		int res = 0;
		if(var1.typeVar.equals(var2.typeVar)){
			res = 1;
			if(var1.placeMemoire != var2.placeMemoire){
				int placememvar1 = var1.placeMemoire;
				var1.placeMemoire = var2.placeMemoire;
				this.getMem(var2.placeMemoire).linkedVars.add(var1);
				EmplacementMemoire mem1 = this.getMem(placememvar1);
				mem1.removeLinkVar(var1.name);
				if(mem1.isNotLinked()){
					//nbMem--;
					this.memoire.remove(mem1);
				}
			}
		}
		return res;
	}
	
	public ArrayList<String> getVarNames(){
		ArrayList<String> res = new ArrayList<String>();
		for(int i=0; i<this.vars.size();i++){
			res.add(this.vars.get(i).name);
		}
		return res;
	}
	
	public VariablePile getVarPile(String varName){
		VariablePile res = null;
		int i = 0;
		boolean found = false;
		while(i<vars.size() && !found){
			if(vars.get(i).name.equals(varName)){
				res = vars.get(i);
				found = true;
			}
			i++;
		}
		return res;
	}

}
